package com.zjitc.serviceedu.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.zjitc.serviceedu.entity.EduOrder;
import com.zjitc.serviceedu.service.EduCourseService;
import com.zjitc.serviceedu.service.EduOrderService;
import com.zjitc.serviceedu.utils.AliPayConfig;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝接口
 */
@RestController
@RequestMapping("/alipay")
@Api(tags = "支付宝支付")
public class AliPayController {

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    @Resource
    private EduOrderService eduOrderService;
    private EduCourseService courseService;

    @GetMapping("/pay")
    @ApiOperation("支付")
    public void pay(@RequestParam String courseTitle, @RequestParam String orderNo, @RequestParam String totalFee, HttpServletResponse httpResponse) throws Exception {
        // 对参数进行编码
        String encodedCourseTitle = URLEncoder.encode(courseTitle, StandardCharsets.UTF_8.toString());
        String encodedOrderNo = URLEncoder.encode(orderNo, StandardCharsets.UTF_8.toString());
        String encodedTotalFee = URLEncoder.encode(totalFee, StandardCharsets.UTF_8.toString());

        // 创建支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getMerchantPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 创建请求并设置参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", encodedOrderNo);
        bizContent.put("total_amount", encodedTotalFee);
        bizContent.put("subject", encodedCourseTitle);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        try {
            String form = alipayClient.pageExecute(request).getBody();
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
        } catch (AlipayApiException e) {
            // 处理异常，记录日志并返回错误响应
            e.printStackTrace();
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "支付请求失败");
        }
        System.out.println("Received courseTitle: " + courseTitle);  // 打印接收到的参数
        System.out.println("Received orderNo: " + orderNo);
        System.out.println("Received totalFee: " + totalFee);

    }

    @PostMapping("/notify") // 注意这里必须是POST接口
    @ApiOperation("支付回调")
    public String payNotify(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            if (values != null && values.length > 0) {
                params.put(name, values[0]); // 确保只取第一个值
            }
        }

        // 确保 trade_status 存在且为 TRADE_SUCCESS
        if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            System.out.println("=========支付宝异步回调========");
            String orderNo = params.get("out_trade_no");

            // 验签
            boolean checkSignature = AlipaySignature.rsaCheckV1(params,
                    aliPayConfig.getAlipayPublicKey(), CHARSET, SIGN_TYPE);

            if (checkSignature) {
                // 更新订单状态为已支付
                boolean isUpdated = eduOrderService.updateOrderStatus(orderNo, 1);
                if (isUpdated) {
                    System.out.println("订单状态已更新为已支付");

                    } else {
                        System.out.println("订单未找到");
                    }
                } else {
                    System.out.println("订单状态更新失败");
                }
            } else {
                System.out.println("验签失败！");
            }
        return "success"; // 确认接收成功
    }
}